package org.redmagic.service.utils;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.google.common.base.Splitter;

public final class ServletUtils {

	private static final Splitter TAGS_SPLITTER = Splitter.on("&").trimResults().omitEmptyStrings();
	private static final Splitter SINGLE_TAG_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
	
	public static String getHostname(HttpServletRequest request) throws UnknownHostException {
		InetAddress address = InetAddress.getByName(request.getRemoteHost());
		String user = address.getHostName();
		return user;
	}
	
	public static String getProperty(HttpServletRequest request, String context) {
		String contextPath = request.getContextPath();
		int length = (contextPath + context).length();
		return (request.getRequestURI().substring(length));
	}
	
	public static List<String> getTags(HttpServletRequest request) {
		// Get the tags from the query parameter.
		String tagString = request.getQueryString();

		List<String> tags = Collections.emptyList();
		if (tagString != null && !tagString.trim().isEmpty()) {
			
			try {
				tagString = URLDecoder.decode(tagString, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException("Unable to decode", e);
			}
			
			tags = parseTags(tagString);
		}
		
		return tags;
	}

	private static List<String> parseTags(String tagString) {
		
		Iterable<String> allTags = TAGS_SPLITTER.split(tagString);
		
		List<String> results = new ArrayList<String>();
		for (String tags : allTags) {
			
			if (tags.startsWith("tags=")) {
				tags = tags.replace("tags=", "");
				Iterable<String> singleTags = SINGLE_TAG_SPLITTER.split(tags);
				for (String singleTag : singleTags) {
					results.add(singleTag);
				}
			} else {
				results.add(tags);
			}
		}
		
		Collections.sort(results);
		return results;
	}
}
